import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)
  
  const isAuthenticated = computed(() => !!token.value)
  const isShopkeeper = computed(() => user.value?.role === 'shopkeeper')
  const isCustomer = computed(() => user.value?.role === 'customer')
  
  const login = (userData) => {
    user.value = userData
    token.value = userData.id.toString()
    localStorage.setItem('token', token.value)
    localStorage.setItem('user', JSON.stringify(userData))
  }
  
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
  
  const initAuth = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
    }
  }
  
  return {
    user,
    token,
    isAuthenticated,
    isShopkeeper,
    isCustomer,
    login,
    logout,
    initAuth
  }
})